package cn.jinhe.doc.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jinhe.doc.base.DaoSupportImpl;
import cn.jinhe.doc.domain.PageBean;
import cn.jinhe.doc.domain.Reply;
import cn.jinhe.doc.domain.Repository;
import cn.jinhe.doc.domain.Topic;
import cn.jinhe.doc.service.ReplyService;
@Service
@Transactional
@SuppressWarnings("unchecked")
public class ReplyServiceImpl extends DaoSupportImpl<Reply> implements ReplyService  {

	@Deprecated
	public List<Reply> findByTopic(Topic topic) {
		// TODO Auto-generated method stub
		return getSession().createQuery(//
				"FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC")
				.setParameter(0, topic)
				.list();
	}
	
	public void save(Reply reply){
		getSession().save(reply);
		
		Topic topic=reply.getTopic();
		Repository repository=topic.getRepository();
		
		repository.setArticleCount(repository.getArticleCount() + 1); // 文章数量（主题数+回复数）
		topic.setReplyCount(topic.getReplyCount() + 1); // 回复数量
		topic.setLastReply(reply); // 最后发表的回复
		topic.setLastUpdateTime(reply.getPostTime()); // 最后更新时间（主题的发表时间或最后回复的时间）

		getSession().update(topic);
		getSession().update(repository);
	}

	@Override
	public PageBean getPageBeanByTopic(int pageNum, int pageSize, Topic topic) {
		// TODO Auto-generated method stub
		List list=getSession().createQuery(//
				"FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC")
				.setParameter(0, topic)//
				.setFirstResult((pageNum-1)*pageSize)
				.setMaxResults(pageSize)
				.list();
		//查询总数量
		Long count = (Long) getSession().createQuery(//
				"SELECT COUNT(*) FROM Reply r WHERE r.topic=?")//
				.setParameter(0, topic)//
				.uniqueResult(); 
		return new PageBean(pageNum, pageSize, list, count.intValue());
	}

}
